package com.itany.mall.dao.mapper;

import java.sql.ResultSet;

import com.itany.mall.entity.Order;
import com.itany.mall.entity.OrderDetail;
import com.itany.mall.entity.Product;
import com.itany.mall.entity.ProductType;
import com.itany.mall.entity.User;
import com.itany.mall.jdbc.template.callback.RowMapper;

public class OrderDetailRowMapper implements RowMapper<OrderDetail> {

	public String selectSql() {
		StringBuffer sql = new StringBuffer();
		sql.append(" select ");
		sql.append("     od.id odid, ");
		sql.append("     od.product_sum, ");
		sql.append("     od.price odprice, ");

		sql.append("     o.id oid, ");
		sql.append("     o.order_num, ");
		sql.append("     o.create_time, ");
		sql.append("     o.price oprice, ");

		sql.append("     p.id pid, ");
		sql.append("     p.name pname, ");
		sql.append("     p.price pprice, ");
		sql.append("     p.num, ");
		sql.append("      ");
		sql.append("     t.id tid, ");
		sql.append("     t.name tname, ");

		sql.append("     u.id uid, ");
		sql.append("     u.name uname, ");
		sql.append("     u.password, ");
		sql.append("     u.phone, ");
		sql.append("     u.email, ");
		sql.append("     u.role ");

		sql.append(" from t_order_detail od ");
		sql.append("     left join t_order o ");
		sql.append("         on od.order_id = o.id ");
		sql.append("     left join t_product p ");
		sql.append("         on od.product_id = p.id ");
		sql.append("     left join t_product_type t ");
		sql.append("         on p.type_id = t.id ");
		sql.append("     left join t_user u ");
		sql.append("         on od.user_id = u.id ");
		return sql.toString();
	}

	@Override
	public OrderDetail mapRow(ResultSet res) throws Exception {
		OrderDetail od = new OrderDetail();

		od.setId(res.getLong("odid"));
		od.setPrice(res.getDouble("odprice"));
		od.setProductSum(res.getInt("product_sum"));

		od.setUserId(res.getLong("uid"));
		User u = new User();
		u.setId(res.getLong("uid"));
		u.setName(res.getString("uname"));
		u.setPassword(res.getString("password"));
		u.setPhone(res.getString("phone"));
		u.setEmail(res.getString("email"));
		u.setRole(res.getInt("role"));
		od.setUser(u);

		od.setOrderId(res.getObject("oid") == null ? null : res.getLong("oid"));
		Order o = new Order();
		o.setId(res.getObject("oid") == null ? null : res.getLong("oid"));
		o.setOrderNum(res.getString("order_num"));
		o.setCreateTime(res.getTimestamp("create_time"));
		o.setPrice(res.getDouble("oprice"));
		o.setUserId(res.getLong("uid"));
		o.setUser(u);
		od.setOrder(o);

		od.setProductId(res.getLong("pid"));
		Product p = new Product();
		p.setId(res.getLong("pid"));
		p.setName(res.getString("pname"));
		p.setPrice(res.getDouble("pprice"));
		p.setNum(res.getInt("num"));
		p.setTypeId(res.getLong("tid"));
		ProductType t = new ProductType();
		t.setId(res.getLong("tid"));
		t.setName(res.getString("tname"));
		p.setType(t);
		od.setProduct(p);

		return od;
	}

}
